package com.touchstone.synchdata.service.impl;

import com.touchstone.synchdata.entity.mssql.Account;
import com.touchstone.synchdata.entity.mysql.User;
import com.touchstone.synchdata.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description : 多数据源业务实现类
 * @Author : hunter
 * @Date: 2020-06-19 15:03
 * @Version: 1.0
 **/
@Slf4j
@Service
public class MultiDataSourceServiceImpl implements IMultiDataSourceService {

    @Resource
    private IMSSQLService mssqlService;
    @Resource
    private IMySQLService mysqlService;
    @Resource
    private IAccountService accountService;
    @Resource
    private IUserService userService;

    @Override
    public Map<String, String> listVersion() {
        Map<String, String> versions = new HashMap<>(3);
        versions.put("MySQL", mysqlService.getVersion());
        versions.put("SQL Server", mssqlService.getVersion());
        return versions;
    }

    @Override
    public List<User> syncAccount2User() {
        List<Account> accounts = accountService.listAccounts();
        List<User> users = userService.listUsers();
        List<User> addUsers = new ArrayList<>();
        for(Account account : accounts) {
            User user = filterUser(users, account.getName());
            if (user == null) {
                user = new User();
                user.setName(account.getName());
                user.setDisabled(account.getDisabled());
                addUsers.add(user);
            }
        }
        if (addUsers.size() > 0) {
            userService.batchSave(addUsers);
        }
        return users;
    }

    private User filterUser (List<User> users, String accountName) {
        User u = null;
        for (User user : users) {
            if (accountName.equals(user.getName())) {
                u = user;
            }
        }
        return u;
    }
}
